.SECONDEXPANSION:

CC = gcc
CFLAGS = -g
CPPFLAGS = 
INCLUDES = -I $(hdrdir)
COMPILE.c = $(CC) $(CFLAGS) $(CPPFLAGS) $(INCLUDES) -c

srcdirs := examples diy
objdir := bin
hdrdir := inc
libdir := lib

MKDIR = mkdir -p
RM = rm -rf

# $(call compile-rules, srcdir, objdir)
define compile-rules
$1_sources = $(wildcard $1/*.c)
$1_objects = $$(patsubst $1/%.c,$2/%.o,$$($1_sources))
$$($1_objects):$2/%.o:$1/%.c | $(objdir)
	$(COMPILE.c) $$< -o $$@
endef

# link individual program with libs. (#srcdir, #libdir)
define link-rules
$1_progs = $(patsubst $(1)/%.c,$(objdir)/%,$(wildcard $1/*.c))
$$($1_progs) : $(objdir)/% : $(objdir)/%.o $$($2_objects) | $(objdir)
	$(CC) $$^ -o $$@
endef

all:

$(eval $(call compile-rules,$(libdir),$(objdir)))
$(foreach parm,$(srcdirs),$(eval $(call compile-rules,$(parm),$(objdir))))

$(foreach parm,$(srcdirs),$(eval $(call link-rules,$(parm),$(libdir))))

total-progs = $(addprefix $(objdir)/,$(foreach parm,$(srcdirs),$(notdir $(subst .c,,$(wildcard $(parm)/*.c)))))
.PHONY: all clean

all: $(total-progs)
	@echo $(total-progs)

$(objdir):
	$(MKDIR) $@

clean:
	$(RM) $(objdir)



